import { insertCart, findCartList, deleteCart, updateCart, checkAllCart } from '@/api/cart'
const cart = {
  namespaced: true, // 命名空间
  state: {
    cartList: [] // 购物车列表
  },
  getters: {
    // 商品总数
    allCount (state) {
      return state.cartList.reduce((a, c) => a + c.count, 0)
    },
    // 总钱数
    allPrice (state) {
      return state.cartList.reduce((a, c) => a + c.count * c.price, 0)
    },
    // 是否全选
    isAll (state) {
      return state.cartList.every(item => item.selected === true)
    },
    // 已选商品总数:在cartList中筛选出来selected为true的项然后把筛选出来数组中的每一项的count值做累加
    selectedCount (state) {
      return state.cartList
        .filter(item => item.selected)
        .reduce((a, c) => a + c.count, 0)
    },
    // 选择商品的价钱
    selectedPrice (state) {
      return state.cartList
        .filter(item => item.selected)
        .reduce((a, c) => a + c.count * c.price, 0)
    }
  },
  mutations: {
    setCartList (state, list) {
      state.cartList = list
    },
    setCount (state, { skuId, count }) {
      // 接收最新count 设置到对应的数据上
      const item = state.cartList.find((item) => item.skuId === skuId)
      item.count = count
    }
  },
  actions: {
    // 加入购物车
    async asyncInsertList (ctx, { skuId, count }) {
      // 1.调用添加购物车接口
      await insertCart({ skuId, count })
      // 2.调用获取购物车列表接口
      const res = await findCartList()
      // 3.调用mutation函数把拿到的list放进去
      ctx.commit('setCartList', res.data.result)
    },
    // 删除购物车
    async asyncDelCart (ctx, ids) {
      await deleteCart(ids)
      // 2.调用获取购物车列表接口
      const res = await findCartList()
      // 3.调用mutation函数把拿到的list放进去
      ctx.commit('setCartList', res.data.result)
    },
    // 单选
    async asyncSingleCheck (ctx, goods) {
      await updateCart(goods)
      // 2.调用获取购物车列表接口
      const res = await findCartList()
      // 3.调用mutation函数把拿到的list放进去
      ctx.commit('setCartList', res.data.result)
    },
    // 全选
    async asyncAllCheck (ctx, selected) {
      // 1. 调接口
      await checkAllCart({
        selected,
        ids: ctx.state.cartList.map((item) => item.skuId)
      })
      // 2.调用获取购物车列表接口
      const res = await findCartList()
      // 3.调用mutation函数把拿到的list放进去
      ctx.commit('setCartList', res.data.result)
    }
  }
}
export default cart
